let EventEmitter = require('events');
let fs = require('mz/fs');
class WriteStream extends EventEmitter {
    constructor(path, options) {
        super();
        this.path = path;
        this.flags = options.flags || 'r';
        this.fd = options.fd || null;
        this.encoding = options.encoding || null;
        this.mode = options.mode || 0o666;
        this.autoClose = options.autoClose || 'true';
        this.start = options.start || 0;
        this.highWaterMark = options.highWaterMark || 64 * 1024;

        this.open()
        this.position = this.start || 0;
        // 需要计算当前写入字节数
        this.len = 0;
        // 是否触发drain事件
        this.needDrain = false;
        // 缓存队列
        this.cache = [];
        // 是否正在写入
        this.writing = false;
    }
    open() {
        console.log(this.path)
        fs.open(this.path, this.flags, this.mode).then(fd => {
            console.log(456);
            this.fd = fd
            this.emit('open')
        }).catch(err => {
            console.log(111)
            return this.emit('error', err)
        })
    }
    write(chunk, encoding = this.encoding, cb = () => { }) {
        chunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
        this.len += chunk.length;
        this.needDrain = this.len >= this.highWaterMark;
        if (this.writing) {
            this.cache.push({
                chunk,
                encoding,
                cb
            })
        } else {
            this.writing = true;
            this._write(chunk, encoding, () => { cb(); this.clearBuffer() })
        }
        return this.needDrain;
    }
    _write(chunk, encoding, clearBuffer) {
        if (typeof this.fd === 'number') {
            return this.once('open', () => this._write(chunk, encoding, clearBuffer))
        }
        console.log(this.fd)
        fs.write(this.fd, chunk, 0, chunk.length, this.position, ( err, bytesWritten ) => {
            this.len -= bytesWritten;
            this.position += bytesWritten;
            console.log(bytesWritten);
            clearBuffer()
        })
    }
    clearBuffer() {
        let obj = this.cache.shift();
        if (obj) {
            this._write(obj.chunk, obj.encoding, () => {
                cb();
                this.clearBuffer();
            })
        } else {
            this.writing = false;
            if (this.needDrain) {
                this.needDrain = false;
                this.emit('drain');
            }
        }
    }
}
module.exports = WriteStream;
